package com.emm.yixun.website.controller.customer;
import java.text.SimpleDateFormat;
//框架包
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.emm.yixun.common.model.enums.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
//common
import com.emm.yixun.common.page.PageUtil;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.model.User;
//website
import com.emm.yixun.website.common.ajax.AjaxRes;
import com.emm.yixun.website.common.utils.base.Const;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.constant.ConstantConfig;
import com.emm.yixun.website.controller.base.BaseController;
import com.emm.yixun.website.utils.ExcelUtil;
import com.emm.yixun.website.utils.QuestionnaireToWordUtil;
import com.emm.yixun.website.vo.customer.QuestionAndAnswersVo;
import com.emm.yixun.website.vo.customer.QuestionAnswerVo;
import com.emm.yixun.website.vo.customer.QuestionVo;
import com.emm.yixun.common.app.servletentity.CustTaglistRes;
import com.emm.yixun.common.model.Project;
import com.emm.yixun.common.model.ProjectAnswer;
import com.emm.yixun.common.model.ProjectQuestion;
//变化的引用
import com.emm.yixun.common.model.ProjectQuestionnaire;
import com.emm.yixun.common.model.ProjectQuestionnaireInfo;
import com.emm.yixun.common.model.QuestionnaireModel;
import com.emm.yixun.common.model.dto.ProjectAnswerDto;
import com.emm.yixun.common.model.dto.ProjectDto;
import com.emm.yixun.common.model.dto.ProjectQuestionDto;
import com.emm.yixun.common.model.dto.ProjectQuestionnaireDto;
import com.emm.yixun.common.model.dto.QuestionnaireModelDto;
import com.emm.yixun.customer.service.ProjectQuestionServiceFacade;
import com.emm.yixun.customer.service.ProjectQuestionnaireServiceFacade;
import com.emm.yixun.customer.service.QuestionnaireModelServiceFacade;
import com.emm.yixun.estate.service.ProjectServiceFacade;
import com.emm.yixun.customer.service.CustTagServiceFacade;
import com.emm.yixun.customer.service.ProjectAnswerServiceFacade;

@Controller
@RequestMapping("/customer/projectQuestionnaire/")
public class ProjectQuestionnaireController extends BaseController<ProjectQuestionnaire>{
	
	@Autowired
	private ProjectQuestionnaireServiceFacade projectQuestionnaireServiceFacade;
	
	@Autowired
	private ProjectQuestionServiceFacade projectQuestionServiceFacade;
	
	@Autowired
	private ProjectAnswerServiceFacade projectAnswerServiceFacade;
	
	@Autowired
	private QuestionnaireModelServiceFacade questionnaireModelServiceFacade;
	
	@Autowired
	private ProjectServiceFacade projectServiceFacade;
	
	@Autowired
	private CustTagServiceFacade custTagServiceFacade;
	
	@Autowired
	private ConstantConfig constantConfig;
	
	@RequestMapping(value="index")
	public String index(ModelMap map){
		//if(doSecurityIntercept(Const.RESOURCES_TYPE_MENU)){
			//判断是否拥有项目列表【全部】权限
	        map.put("permitBtn", doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "customer:list:all"));		
			//查询项目
			User user=ShiroUtil.getCurrentUser();
			ProjectDto entity = new ProjectDto();
			entity.setMerchantId(user.getMerchantId());
			entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
			entity.setResourcesCode("menu_0003_0001");
			entity.setPermissionUserId(user.getId());
			ResponseList<Project> res = projectServiceFacade.findByDto(entity);
			List<Project> projectList = new ArrayList<Project>();
			if(res.isSuccess() && null != res.getEntity() && res.getEntity().size() > 0){
				projectList = res.getEntity();
			}
			map.addAttribute("projectList", projectList);
			//获取h5问卷地址
			map.addAttribute("questionnaireH5", constantConfig.getQuestionnaireH5());
			
			return "/system/questionnaire/project/project_questionnaire_list";
	//	}
		//return Const.NO_AUTHORIZED_URL;
	}
	
	/**
	 * 跳转问卷模板新增页面
	 * @param map
	 * @return
	 */
	@RequestMapping(value="toAdd")
	public String toAdd(ModelMap map, Long modelId){
		//if(doSecurityIntercept(Const.RESOURCES_TYPE_MENU)){
			User user=ShiroUtil.getCurrentUser();
			//获取创建人信息
			map.addAttribute("userId", user.getId());
			map.addAttribute("userName", user.getUserName());
			//获取创建时间
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			map.addAttribute("createTime", sdf.format(Calendar.getInstance().getTime()));
			//获取问卷类型
			//获取问卷类型
			if(MerchantEnum.GREEN_TOWN.getNo().equals(String.valueOf(user.getMerchantId()))
					|| MerchantEnum.GREEN_TOWN_TEST.getNo().equals(String.valueOf(user.getMerchantId()))){
				map.addAttribute("questionnaireType", QuestionnaireTypeEnum.values());
			}else{
				map.addAttribute("questionnaireType", QuestionnaireTypeNormalEnum.values());
			}

			//查询项目
			ProjectDto entity = new ProjectDto();
			entity.setMerchantId(user.getMerchantId());
			entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
			ResponseList<Project> res = projectServiceFacade.findByDto(entity);
			List<Project> projectList = new ArrayList<Project>();
			if(res.isSuccess()){
				projectList = res.getEntity();
			}
			map.addAttribute("projectList", projectList);
			
			return "/system/questionnaire/project/project_questionnaire_add";
		//}
		//return Const.NO_AUTHORIZED_URL;
	}
	
	/**
	 * 查询模板
	 * @param questionnaireType 问卷类型
	 * @return
	 */
	@RequestMapping(value="getModel", method=RequestMethod.POST)
	@ResponseBody
	public AjaxRes getModel(String questionnaireType) {
		AjaxRes ar=getAjaxRes();
    	
        try {
        	User user=ShiroUtil.getCurrentUser();
			//查询模板
			QuestionnaireModelDto dto = new QuestionnaireModelDto();
			dto.setMerchantId(user.getMerchantId());
			dto.setType(questionnaireType);
			dto.setIsValid(IsValidEnum.VALID.getNo());
			dto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			ResponseList<QuestionnaireModel> response = questionnaireModelServiceFacade.findByDto(dto);
			if(response.isSuccess()){
				ar.setSucceed(response.getEntity());
			}
		} catch (Exception e) {
			logger.error(e.toString(),e);
			ar.setFailMsg(Const.SAVE_FAIL);
		}
		return ar;
	}
	
	/**
	 * 新增返回实体对象
	 * @param dto
	 * @param modelId 模板ID
	 * @return
	 */
	@RequestMapping(value="add", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  add(ProjectQuestionnaireDto dto, Long modelId){
    	AjaxRes ar=getAjaxRes();
    	
    	/*
    	 *1.判断权限 
    	 *2.调用新增接口
    	 *3.返回信息
    	*/
       // if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:projectQuestionnaire:add"))){
        	try {
        		User user=ShiroUtil.getCurrentUser();
        		dto.setUserCode(user.getUserCode());
        		dto.setMerchantId(user.getMerchantId());
        		dto.setCreateUser(user.getId());
        		dto.setDelFlag("0");
				Response<ProjectQuestionnaireDto> response = 
						projectQuestionnaireServiceFacade.saveInfo(dto, modelId, null);
				if(response.isSuccess()){
					ar.setSucceedMsg(Const.SAVE_SUCCEED);
				}else{
					ar.setFailMsg(response.getResultMessage());
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.SAVE_FAIL);
			}
    	//}
    	return ar;
    }
	
	/**
	 * 弹出复制问卷框
	 * @param id
	 * @param map
	 * @return
	 */
	@RequestMapping(value="toCopy")
	public String toCopy(Long id, String flag, String type, ModelMap map){
		//if(doSecurityIntercept(Const.RESOURCES_TYPE_MENU)){
			//查询模板名称及模板描述
			Response<ProjectQuestionnaire> response = projectQuestionnaireServiceFacade.findById(id);
			if(response.isSuccess() && response.getEntity() != null){
				ProjectQuestionnaire pq = response.getEntity();
				map.addAttribute("copyId", id);
				//问卷类型
				map.addAttribute("type", type);
				map.addAttribute("name", pq.getName() + "_副本");
				map.addAttribute("describe", 
						StringUtils.isBlank(pq.getQuestionnaireDescribe()) ?
								"" : pq.getQuestionnaireDescribe());
				map.addAttribute("projectId", pq.getProjectId());
			}
			//获取修改人信息
			User user=ShiroUtil.getCurrentUser();
			map.addAttribute("userId", user.getId());
			map.addAttribute("userName", user.getUserName());
			//获取修改时间
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			map.addAttribute("createTime", sdf.format(Calendar.getInstance().getTime()));
			//查询项目
			ProjectDto entity = new ProjectDto();
			entity.setMerchantId(user.getMerchantId());
			entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
			ResponseList<Project> res = projectServiceFacade.findByDto(entity);
			List<Project> projectList = new ArrayList<Project>();
			if(res.isSuccess() && res.getEntity().size() > 0){
				projectList = res.getEntity();
			}
			map.addAttribute("projectList", projectList);
			//判断是否需要刷新列表
			map.addAttribute("flag", flag);
			
			return "/system/questionnaire/project/project_questionnaire_copy";
		//}
		//return Const.NO_AUTHORIZED_URL;
	}
	
	/**
	 * 复制问卷模板
	 * @param dto
	 * @param copyId
	 * @return
	 */
	@RequestMapping(value="copy", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes copy(ProjectQuestionnaireDto dto, long copyId, String type){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用修改接口
    	 *3.返回信息
    	*/
        //if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:questionnaireModel:edit"))){
        	try {
        		User user=ShiroUtil.getCurrentUser();
        		dto.setUserCode(user.getUserCode());
        		dto.setMerchantId(user.getMerchantId());
        		dto.setCreateUser(user.getId());
        		dto.setType(type);
        		//dto.setIsValid(IsValidEnum.UNVALID.getNo()); //默认无效（未启用）
        		dto.setDelFlag("0");
				Response<ProjectQuestionnaireDto> response = projectQuestionnaireServiceFacade
						.saveInfo(dto, null, copyId);
				if(response.isSuccess()){
					ar.setSucceedMsg(Const.SAVE_SUCCEED);
				}else{
					ar.setFailMsg(response.getResultMessage());
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.UPDATE_FAIL);
			}
    	//}
    	return ar;
    }
	
	//查看
	@RequestMapping(value="view", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  view(Long id){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用查看接口
    	 *3.返回信息
    	*/
        //if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:projectQuestionnaire:view"))){
        	try {
				Response<ProjectQuestionnaire> response=projectQuestionnaireServiceFacade.findById(id);
				if(response.isSuccess()){
					ar.setSucceed(response.getEntity());
				}else {
					ar.setFailMsg(Const.DATA_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
    	//}
    	return ar;
    }
	
	/**
	 * 跳转问卷模板新增页面
	 * @param map
	 * @return
	 */
	@RequestMapping(value="toEdit")
	public String toEdit(ModelMap map, Long projectQuestionnaireId, String flag){
		//if(doSecurityIntercept(Const.RESOURCES_TYPE_MENU)){
			//查询模板名称、模板描述及是否启用
			String name = "", describe = "", isValid = "";
			if(projectQuestionnaireId != null){
				Response<ProjectQuestionnaire> response = 
						projectQuestionnaireServiceFacade.findById(projectQuestionnaireId);
				if(response.isSuccess() && response.getEntity() != null){
					name = response.getEntity().getName();
					describe = StringUtils.isBlank(response.getEntity().getQuestionnaireDescribe()) ?
									"" : response.getEntity().getQuestionnaireDescribe();
					isValid = response.getEntity().getIsValid();
					map.addAttribute("projectId", response.getEntity().getProjectId());
				}
			}
			map.addAttribute("projectQuestionnaireId", projectQuestionnaireId);
			map.addAttribute("name", name);
			map.addAttribute("describe", describe);
			map.addAttribute("isValid", isValid);
			//获取创建人信息
			User user=ShiroUtil.getCurrentUser();
			map.addAttribute("userId", user.getId());
			map.addAttribute("userName", user.getUserName());
			//获取创建时间
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
			map.addAttribute("createTime", sdf.format(Calendar.getInstance().getTime()));
			//查询项目
			ProjectDto entity = new ProjectDto();
			entity.setMerchantId(user.getMerchantId());
			entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
			ResponseList<Project> res = projectServiceFacade.findByDto(entity);
			List<Project> projectList = new ArrayList<Project>();
			if(res.isSuccess() && res.getEntity().size() > 0){
				projectList = res.getEntity();
			}
			map.addAttribute("projectList", projectList);
			
			return "/system/questionnaire/project/project_questionnaire_edit";
		//}
		//return Const.NO_AUTHORIZED_URL;
	}
	
	//修改
	@RequestMapping(value="edit", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  edit(ProjectQuestionnaireDto dto){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用修改接口
    	 *3.返回信息
    	*/
        //if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:projectQuestionnaire:edit"))){
        	try {
        		Response<Integer> response=projectQuestionnaireServiceFacade.updateByPrimaryKey(dto, true);
				if(response.isSuccess()){
					ar.setSucceedMsg(Const.UPDATE_SUCCEED);
				}else{
					ar.setFailMsg(Const.UPDATE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.UPDATE_FAIL);
			}
    	//}
    	return ar;
    }
	
	//删除
	@RequestMapping(value="delete", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  delete(Long id){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用查看接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:projectQuestionnaire:delete"))){
        	try {
        		Response<Integer> response=projectQuestionnaireServiceFacade.deleteByPrimaryKey(id);
				if(response.isSuccess()){
					ar.setSucceedMsg(Const.DEL_SUCCEED);
				}else {
					ar.setFailMsg(Const.DEL_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DEL_FAIL);
			}
    	}
    	return ar;
    }
	
	//分页查询
	@RequestMapping(value="list", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  list(ProjectQuestionnaireDto dto,Integer pageSize,Integer pageNum){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用分页查询接口
    	 *3.返回信息
    	*/
        //if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"estate:project:list"))){
        	try {
        		dto.addDesc("create_time");
        		User user = ShiroUtil.getCurrentUser();
        		dto.setPermissionUserId(user.getId());
        		dto.setMerchantId(user.getMerchantId());
        		Page<ProjectQuestionnaireInfo> response=projectQuestionnaireServiceFacade.findPageInfoByDto(dto, PageUtil.begin(pageNum, pageSize),pageSize);
                if(response.getSuccess()){
                    if(null==response.getRows()) {
                        response.setRows(new ArrayList<ProjectQuestionnaireInfo>());
                    }
                	response.setPageNumber(pageNum);
                	ar.setSucceed(response);
                }else{
                	ar.setFailMsg(Const.DATA_FAIL);
                }
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
    	//}
    	return ar;
    }
	
	/**
	 * 问卷填写记录
	 * @param dto
	 * @param pageSize
	 * @param pageNum
	 * @return
	 */
	@RequestMapping(value="historicalRecord", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes historicalRecord(HttpServletRequest request,ProjectQuestionnaireDto dto,Integer pageSize,Integer pageNum){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用分页查询接口
    	 *3.返回信息
    	*/
        //if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"estate:project:historicalRecord"))){
        	try {
        		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        		//填写开始时间
        		String startTime = request.getParameter("startTime");
        		if(StringUtils.isNotBlank(startTime)){
        			startTime = startTime + " 00:00:00"; 
        			dto.setCreateTimeBefore(sdf.parse(startTime));
        		}
        		//填写结束时间
        		String endTime = request.getParameter("endTime");
        		if(StringUtils.isNotBlank(endTime)){
        			endTime = endTime + " 23:59:59";
        			dto.setCreateTimeAfter(sdf.parse(endTime));
        		}
        		dto.addDesc("create_time");
        		User user = ShiroUtil.getCurrentUser();
        		dto.setPermissionUserId(user.getId());
        		dto.setMerchantId(user.getMerchantId());
        		Page<ProjectQuestionnaireInfo> response=projectQuestionnaireServiceFacade.findCustomerPageInfoByDto(dto, PageUtil.begin(pageNum, pageSize),pageSize);
                if(response.getSuccess()){
                    if(null==response.getRows()){
                        response.setRows(new ArrayList<ProjectQuestionnaireInfo>());
                    }
                	response.setPageNumber(pageNum);
                	ar.setSucceed(response);
                }else{
                	ar.setFailMsg(Const.DATA_FAIL);
                }
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
    	//}
    	return ar;
    }
	
	/**
	 * 跳转问卷模板预览页面
	 * @param id
	 * @param map
	 * @return
	 */
	@RequestMapping(value="toView")
	public String toView(Long projectQuestionnaireId, ModelMap map){
		//if(doSecurityIntercept(Const.RESOURCES_TYPE_MENU)){
			map.addAttribute("projectQuestionnaireId", projectQuestionnaireId);
			//查询模板名称及模板描述
			Response<ProjectQuestionnaire> response = projectQuestionnaireServiceFacade
					.findById(projectQuestionnaireId);
			if(response.isSuccess() && response.getEntity() != null){
				map.addAttribute("name", response.getEntity().getName());
			}
			return "/system/questionnaire/project/project_questionnaire_view";
		//}
		//return Const.NO_AUTHORIZED_URL;
	}
	
	/**
	 * 跳转问卷模板编辑页
	 * @param id
	 * @param type
	 * @param map
	 * @return
	 */
	@RequestMapping(value="toQuestionEdit")
	public String toQuestionEdit(Long projectQuestionnaireId, ModelMap map){
		//if(doSecurityIntercept(Const.RESOURCES_TYPE_MENU)){
			map.addAttribute("projectQuestionnaireId", projectQuestionnaireId);
			//问卷地址
			String url = "/system/questionnaire/project/project_question_bank_edit";
			//查询模板名称及模板描述
			Response<ProjectQuestionnaireInfo> response = projectQuestionnaireServiceFacade
					.findByIdInfo(projectQuestionnaireId);
			if(response.isSuccess() && response.getEntity() != null){
				map.addAttribute("name", response.getEntity().getName());
				map.addAttribute("describe", 
						StringUtils.isBlank(response.getEntity().getQuestionnaireDescribe()) ?
								"" : response.getEntity().getQuestionnaireDescribe());
				map.addAttribute("projectId", response.getEntity().getProjectId());
				map.addAttribute("isValid", response.getEntity().getIsValid());
				map.addAttribute("fillInNum", response.getEntity().getFillInNum());
				//问卷类型不等于题库选题时，跳转自定义问卷
				if(!QuestionnaireTypeEnum.QUESTIONBANK.getNo()
				        .equals(response.getEntity().getType())){
				    url = "/system/questionnaire/project/project_question_edit";
				}
			}
			//获取修改人信息
			User user=ShiroUtil.getCurrentUser();
			map.addAttribute("userId", user.getId());
			map.addAttribute("userName", user.getUserName());
			//获取修改时间
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			map.addAttribute("createTime", sdf.format(Calendar.getInstance().getTime()));
			
			return url;
		//}
		//return Const.NO_AUTHORIZED_URL;
	}
	
	/**
	 * 导出模板问卷至Word
	 * @param dto
	 * @param request
	 * @param respnse
	 */
	@RequestMapping(value="exportToWord", method=RequestMethod.GET)
    public void exportToWord(ProjectQuestionnaireDto dto, HttpServletRequest request, HttpServletResponse response){
    	try{
    		QuestionAndAnswersVo qaaVo = new QuestionAndAnswersVo();
    		long projectQuestionnaireId = dto.getId();
    		//问卷信息
    		Response<ProjectQuestionnaire> qmRes = projectQuestionnaireServiceFacade.findById(projectQuestionnaireId);
    		String title = "";
    		String desc = "";
    		if(qmRes.isSuccess()){
    			ProjectQuestionnaire qm = qmRes.getEntity();
    			title = qm.getName();
    			desc = qm.getQuestionnaireDescribe();
    			qaaVo.setTitle(title);
    			qaaVo.setDesc(desc);
    		}
    		//问卷题目
    		List<ProjectQuestion> qqList = new ArrayList<ProjectQuestion>();
    		ProjectQuestionDto qqDto = new ProjectQuestionDto();
    		qqDto.setProjectQuestionnaireId(projectQuestionnaireId);
    		qqDto.setIsValid(IsValidEnum.VALID.getNo());
    		qqDto.setOrders("sort asc");
    		ResponseList<ProjectQuestion> qmResList = projectQuestionServiceFacade.findByDto(qqDto);
    		if(qmResList.isSuccess()){
    			qqList = qmResList.getEntity();
    		}
    		//题目答案
    		List<ProjectAnswer> qaList = new ArrayList<ProjectAnswer>();
    		ProjectAnswerDto qaDto = new ProjectAnswerDto();
    		qaDto.setQuestionnaireId(projectQuestionnaireId);
    		qaDto.setIsValid(IsValidEnum.VALID.getNo());
    		qaDto.setOrders("sort asc");
    		ResponseList<ProjectAnswer> qaResList = projectAnswerServiceFacade.findByQuestionnaireId(qaDto);
    		if(qaResList.isSuccess()){
    			qaList = qaResList.getEntity();
    		}
    		if(null != qqList && qqList.size() > 0){
    			List<QuestionVo> questionVoList = new ArrayList<QuestionVo>();
    			for(ProjectQuestion qq: qqList){
    				String questionId = String.valueOf(qq.getId());
    				QuestionVo questionVo = new QuestionVo();
    				questionVo.setId(questionId);
    				questionVo.setQuestion(qq.getQuestion());
    				questionVo.setQuestionDesc(qq.getQuestionnaireDescribe());
    				questionVo.setProblemCode(qq.getProblemCode());
    				questionVo.setAnswerType(qq.getAnswerType());
    				List<QuestionAnswerVo> qaVoList = new ArrayList<QuestionAnswerVo>();
    				if(null != qaList && qaList.size() > 0){
    					for(ProjectAnswer qa: qaList){
    						String qaQuestionId = String.valueOf(qa.getProjectQuestionId());
    						if(questionId.equals(qaQuestionId)){
    							QuestionAnswerVo qaVo = new QuestionAnswerVo();
        						qaVo.setQuestionId(questionId);
        						qaVo.setAnswer(qq.getAnswerType());
        						qaVo.setAnswer(qa.getAnswer());
        						qaVo.setSort(String.valueOf(qa.getSort()));
        						qaVoList.add(qaVo);
    						}
    					}
    				}
    				//题目选项列表
    				questionVo.setQuestionAnswerList(qaVoList);
    				//题目列表
    				questionVoList.add(questionVo);
    			}
    			qaaVo.setQuestionList(questionVoList);
    		}
    		//调用导出方法
    		QuestionnaireToWordUtil.exportWord(qaaVo, response);
    	}catch(Exception ex){
    		ex.printStackTrace();
    		logger.error("导出问卷模板至Word: ", ex);
    	}
    }
	
	/**
	 * 问卷分析
	 * @param map
	 * @return
	 */
	@RequestMapping(value="analyzeList")
	public String analyzeList(ModelMap map){
		//if(doSecurityIntercept(Const.RESOURCES_TYPE_MENU)){
			//判断是否拥有项目列表【全部】权限
	        map.put("permitBtn", doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "customer:list:all"));   	
			//查询项目
			User user=ShiroUtil.getCurrentUser();
			ProjectDto entity = new ProjectDto();
			entity.setMerchantId(user.getMerchantId());
			entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
			entity.setResourcesCode("menu_0003_0001");
			entity.setPermissionUserId(user.getId());
			ResponseList<Project> res = projectServiceFacade.findByDto(entity);
			List<Project> projectList = new ArrayList<Project>();
			if(res.isSuccess() && null != res.getEntity() && res.getEntity().size() > 0){
				projectList = res.getEntity();
			}
			map.addAttribute("projectList", projectList);
			
			return "/system/questionnaire/project/project_questionnaire_analyze_list";
	//	}
		//return Const.NO_AUTHORIZED_URL;
	}
	
	/**
	 * 跳转问卷模板预览页面
	 * @param id
	 * @param map
	 * @return
	 */
	@RequestMapping(value="toAnalyzeView")
	public String toAnalyzeView(Long projectQuestionnaireId, ModelMap map){
		//if(doSecurityIntercept(Const.RESOURCES_TYPE_MENU)){
			map.addAttribute("projectQuestionnaireId", projectQuestionnaireId);
			//查询模板名称及模板描述
			Response<ProjectQuestionnaireInfo> response = projectQuestionnaireServiceFacade
					.findByIdInfo(projectQuestionnaireId);
			
			if(response.isSuccess() && response.getEntity() != null){
				map.addAttribute("name", response.getEntity().getName());
				map.addAttribute("fillInNum", response.getEntity().getFillInNum());
				Response<Project> projectRes = projectServiceFacade.findById(response.getEntity().getProjectId());
				if(projectRes.isSuccess() && projectRes.getEntity() != null){
					map.addAttribute("projectName", projectRes.getEntity().getProjectName());
				}
			}
			return "/system/questionnaire/project/analyze_view";
		//}
		//return Const.NO_AUTHORIZED_URL;
	}
	
	/**
	 * 导出填写记录到excel
	 * @param dto
	 * @param request
	 * @param respnse
	 */
	@RequestMapping(value="historicalRecordExport", method=RequestMethod.GET)
    public String historicalRecordExport(Long questionnaireId, HttpServletRequest request, HttpServletResponse response, ModelMap modelMap){
		//查询模板名称
		Response<ProjectQuestionnaire> resNaire = projectQuestionnaireServiceFacade
				.findById(questionnaireId);
		if(!resNaire.isSuccess()) {
			modelMap.addAttribute("9999", "导出失败，该问卷已被删除");
			return "/system/questionnaire/project/project_questionnaire_list";
		}
		ProjectQuestionnaire naire = resNaire.getEntity();
		
		//组装导出数据
		String[] name = new String[]{naire.getName()}; //sheet
		List<String[]> headerList = new ArrayList<String[]>(); //表头
		List<List<Map<String, String>>> list = new ArrayList<List<Map<String, String>>>(); //数据
		
		ProjectQuestionDto entity = new ProjectQuestionDto();
		entity.setProjectQuestionnaireId(questionnaireId);
		entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
		ResponseList<ProjectQuestion> resList = projectQuestionServiceFacade.findByDto(entity);
		if(!resList.isSuccess()) {
			modelMap.addAttribute("9999", "导出失败，该问卷已被删除");
			return "/system/questionnaire/project/project_questionnaire_list";
		}
		//设置问卷题目为表头（前4为固定表头，后面为动态拼接的问卷题目）
		String[] header = new String[4 + resList.getEntity().size()];
		header[0] = "客户姓名";
		header[1] = "客户电话";
		header[2] = "经纪人";
		header[3] = "填写时间";
		for(int i = 0; i < resList.getEntity().size(); i++) {
			ProjectQuestion pq = resList.getEntity().get(i);
			header[i + 4] = pq.getQuestion();
		}
		headerList.add(header);
		
		//获取问卷填写内容，全部存入map，减少对数据库查询操作
		Map<String, String> ctMap = new HashMap<String, String>();
		List<CustTaglistRes> res = custTagServiceFacade
				.getCustomerAnswerList(naire.getProjectId(), questionnaireId);
		for(CustTaglistRes ct : res) {
			StringBuffer key = new StringBuffer();
			key.append(ct.getCustomerName());
			key.append("_");
			key.append(ct.getCustomerPhone());
			key.append("_");
			key.append(ct.getTagName());
			ctMap.put(key.toString(), ct.getTagValue());
		}

		SimpleDateFormat sft = new SimpleDateFormat("yyyy-MM-dd");
		List<Map<String, String>> mapList = new ArrayList<Map<String, String>>();
		//获取填写问卷的客户信息
		ResponseList<ProjectQuestionnaireInfo> cusList = projectQuestionnaireServiceFacade
				.getCustomerInfoList(naire.getProjectId(), questionnaireId);
		for(int i = 0; i < cusList.getEntity().size(); i++) {
			ProjectQuestionnaireInfo info = (ProjectQuestionnaireInfo)cusList.getEntity().get(i);
			Map<String, String> map = new HashMap<String, String>();
			map.put(header[0]+"_"+i, info.getCustomerName());
			map.put(header[1]+"_"+i, info.getCustomerPhone());
			map.put(header[2]+"_"+i, info.getAgentName());
			map.put(header[3]+"_"+i, sft.format(info.getCreateTime()));
			for(int j = 4; j < header.length; j++) {
				StringBuffer value = new StringBuffer();
				value.append(info.getCustomerName());
				value.append("_");
				value.append(info.getCustomerPhone());
				value.append("_");
				value.append(header[j]);
				map.put(header[j]+"_"+i, ctMap.get(value.toString()));
			}
			mapList.add(map);
		}
		list.add(mapList);
		//导出excel
		ExcelUtil.exportExcel(list, headerList, name, response);
		
		return null;
	}
}
